package com.ch.d0301;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "CookieServlet", value = "/CookieServlet")
public class CookieServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        //获取cookie数据
        final Cookie[] cookies = request.getCookies();
        //没有cookie数据，该数组为空
        final PrintWriter out = response.getWriter();
        if(cookies!=null){
            out.print("<ul>");
            for (Cookie cookie : cookies){
                out.printf("<li>%s : %s</li>",cookie.getName(),cookie.getValue());
            }
            out.print("</ul>");

        }
        String name = request.getParameter("name");
        //服务器向浏览器发送cookie数据
        Cookie cookie = new Cookie("name","zhangsan");
        // 有限期: 单位 秒 一周，  有限期为0 表示 删除该cookie

        if(name == null){
            cookie.setMaxAge(0);
        }else{
            cookie.setMaxAge(60 * 60 * 24 *7);
        }
        //cookie.setPath(); 路径，默认当前路径
        //cookie.setDomain(); 域名 ==> 同源策略
        response.addCookie(cookie);

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
